Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : ORIX App Universe8 * File : src/app/api/admin/[...path]/route.ts9 * Module : app10 * Repository : https://git.spboucher.ai/orix-spboucher-ai11 * Project Website : https://www.orixlab.dev12 * Created : 2026-11-2113 * Last Modified : 2026-11-2114 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: support@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243import { setDefaultAutoSelectFamilyAttemptTimeout } from "node:net";44import { audit, recentAudit } from "@/lib/audit";45import { requireAdmin, type AdminContext } from "@/lib/auth/session";46import { createApp, discardDraft, getApp, listApps, publishApp, saveDraft, setPublish } from "@/lib/catalog";47import { db, now, setSetting } from "@/lib/database/db";48import { totals } from "@/lib/downloads/metrics";49import { approveRelease, requeueRelease, setReleaseNotes, withdrawRelease } from "@/lib/releases/pipeline";50import { allReleases } from "@/lib/releases/store";51import { recentRuns, runSync } from "@/lib/releases/sync";52import { ApiError, clientIp, json, readJson, route } from "@/lib/security/http";53import { checkInvite, isPublicInvite } from "@/lib/testflight";54import { storeImage } from "@/lib/uploads";55import { AppDoc } from "@/models/app";5657type Ctx = { req: Request; admin: AdminContext; ip: string };58const SLUG = /^[a-z][a-z0-9-]{1,30}$/;5960async function apps(c: Ctx, [slug, sub]: string[]): Promise<Response> {61 const { req, admin, ip } = c;62 if (!slug) {63 if (req.method === "GET") return json({ apps: listApps({ all: true }).map((r) => ({ slug: r.slug, name: r.app.name, publish: r.publish, hasDraft: r.hasDraft, status: r.app.status, updatedAt: r.updatedAt })) });64 const b = await readJson<{ slug?: string; name?: string }>(req);65 if (!b.slug || !SLUG.test(b.slug) || !b.name?.trim()) throw new ApiError(422, "invalid", "A slug (a-z, 0-9, -) and a name are required");66 createApp(b.slug, b.name.trim()); audit("app.created", { actor: admin.adminId, ip, detail: { slug: b.slug } });67 return json({ ok: true, slug: b.slug }, { status: 201 });68 }69 if (!SLUG.test(slug)) throw new ApiError(404, "not_found");70 const row = getApp(slug, { all: true, preview: true });71 if (!row) throw new ApiError(404, "not_found", "Unknown application");72 if (!sub) {73 if (req.method === "GET") return json(row);74 if (req.method === "PUT") { const doc = saveDraft(slug, await readJson(req)); audit("app.draft_saved", { actor: admin.adminId, ip, detail: { slug } }); return json({ ok: true, app: doc }); }75 }76 if (req.method !== "POST") throw new ApiError(405, "method");77 switch (sub) {78 case "publish": publishApp(slug); break;79 case "unpublish": setPublish(slug, "draft"); break;80 case "archive": setPublish(slug, "archived"); break;81 case "discard": discardDraft(slug); break;82 case "media": {83 const form = await req.formData(), file = form.get("file"), kind = form.get("kind") === "icon" ? "icon" : "screenshot";84 if (!(file instanceof File)) throw new ApiError(422, "invalid", "No file");85 const stored = await storeImage(slug, Buffer.from(await file.arrayBuffer()), kind);86 audit("media.uploaded", { actor: admin.adminId, ip, detail: { slug, kind, file: stored.file } });87 return json({ ok: true, ...stored });88 }89 case "testflight": {90 // Verifies the invitation of the working copy and records the result in the draft.91 const doc = AppDoc.parse(row.app), d = doc.distribution.find((x) => x.channel === "testflight");92 if (!d || !isPublicInvite(d.url)) throw new ApiError(422, "no_invite", "Save a public TestFlight invitation URL (https://testflight.apple.com/join/…) first");93 d.check = await checkInvite(d.url);94 saveDraft(slug, doc); audit("testflight.checked", { actor: admin.adminId, ip, detail: { slug, result: d.check.result } });95 return json({ ok: true, check: d.check });96 }97 default: throw new ApiError(404, "not_found");98 }99 audit(`app.${sub}`, { actor: admin.adminId, ip, detail: { slug } });100 return json({ ok: true });101}102103// The first address tried towards Apple can take seconds from this network; the 250 ms default gives up too early.104setDefaultAutoSelectFamilyAttemptTimeout(2500);105106async function releases({ req, admin }: Ctx, [id, action]: string[]): Promise<Response> {107 if (!id) return json({ releases: allReleases() });108 if (req.method !== "POST" || !/^\d+$/.test(id)) throw new ApiError(404, "not_found");109 const n = Number(id);110 switch (action) {111 case "approve": return json({ ok: true, release: await approveRelease(n, admin.adminId) });112 case "withdraw": return json({ ok: true, release: await withdrawRelease(n, admin.adminId) });113 case "requeue": return json({ ok: true, release: requeueRelease(n, admin.adminId) });114 case "notes": { const b = await readJson<{ en?: string; fr?: string }>(req); setReleaseNotes(n, { en: String(b.en ?? "").slice(0, 4000), fr: String(b.fr ?? "").slice(0, 4000) }); return json({ ok: true }); }115 default: throw new ApiError(404, "not_found");116 }117}118119const KINDS = ["announcement", "new-app", "update", "beta", "release"];120async function announcements({ req, admin, ip }: Ctx, [id]: string[]): Promise<Response> {121 const d = db();122 if (req.method === "GET") return json({ announcements: d.prepare("SELECT * FROM announcements ORDER BY date DESC, id DESC").all() });123 if (req.method === "DELETE" && /^\d+$/.test(id ?? "")) { d.prepare("DELETE FROM announcements WHERE id = ?").run(Number(id)); audit("announcement.deleted", { actor: admin.adminId, ip, detail: { id } }); return json({ ok: true }); }124 const b = await readJson<Record<string, string>>(req);125 const v = { kind: KINDS.includes(b.kind) ? b.kind : "announcement", app_slug: b.app_slug && getApp(b.app_slug, { all: true }) ? b.app_slug : null, date: /^\d{4}-\d{2}-\d{2}$/.test(b.date ?? "") ? b.date : now().slice(0, 10),126 publish: ["draft", "published", "archived"].includes(b.publish) ? b.publish : "draft", title_en: String(b.title_en ?? "").trim().slice(0, 200), title_fr: String(b.title_fr ?? "").trim().slice(0, 200), body_en: String(b.body_en ?? "").trim().slice(0, 6000), body_fr: String(b.body_fr ?? "").trim().slice(0, 6000) };127 if (v.publish === "published" && (!v.title_en || !v.title_fr || !v.body_en || !v.body_fr)) throw new ApiError(422, "not_publishable", "A published announcement needs a title and a text in both languages");128 if (req.method === "POST" && !id) {129 const r = d.prepare("INSERT INTO announcements (kind, app_slug, date, publish, title_en, title_fr, body_en, body_fr, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(v.kind, v.app_slug, v.date, v.publish, v.title_en, v.title_fr, v.body_en, v.body_fr, now(), now());130 audit("announcement.created", { actor: admin.adminId, ip, detail: { id: Number(r.lastInsertRowid), publish: v.publish } });131 return json({ ok: true, id: Number(r.lastInsertRowid) }, { status: 201 });132 }133 if (req.method === "PUT" && /^\d+$/.test(id ?? "")) {134 d.prepare("UPDATE announcements SET kind = ?, app_slug = ?, date = ?, publish = ?, title_en = ?, title_fr = ?, body_en = ?, body_fr = ?, updated_at = ? WHERE id = ?").run(v.kind, v.app_slug, v.date, v.publish, v.title_en, v.title_fr, v.body_en, v.body_fr, now(), Number(id));135 audit("announcement.updated", { actor: admin.adminId, ip, detail: { id, publish: v.publish } });136 return json({ ok: true });137 }138 throw new ApiError(405, "method");139}140141/** The whole administrative API. Nothing below runs without a live session; writes also need the CSRF token. */142const handle = route(async (req, { params }: { params: Promise<{ path: string[] }> }) => {143 const admin = await requireAdmin(req);144 const [head, ...rest] = (await params).path;145 const c: Ctx = { req, admin, ip: clientIp(req) };146 switch (head) {147 case "apps": return apps(c, rest);148 case "releases": return releases(c, rest);149 case "announcements": return announcements(c, rest);150 case "sync":151 if (req.method === "GET") return json({ runs: recentRuns() });152 audit("sync.manual", { actor: admin.adminId, ip: c.ip });153 try { return json(await runSync({ trigger: "manual" })); } catch (e) { throw new ApiError(409, "sync_busy", e instanceof Error ? e.message : "sync failed"); }154 case "settings": {155 const b = await readJson<{ requireNotarization?: boolean }>(req);156 if (typeof b.requireNotarization === "boolean") { setSetting("publication.requireNotarization", b.requireNotarization ? "1" : "0"); audit("settings.requireNotarization", { actor: admin.adminId, ip: c.ip, detail: b.requireNotarization }); }157 return json({ ok: true });158 }159 case "metrics": return json({ totals: totals() });160 case "audit": return json({ audit: recentAudit() });161 default: throw new ApiError(404, "not_found");162 }163});164export { handle as GET, handle as POST, handle as PUT, handle as DELETE };165